<?php

namespace app\api\middleware;

use app\api\service\Token;
use app\facade\Basic;
use think\facade\Cookie;

class Auth
{
    public function handle($request,\Closure $next){


        // Token 不存在
        $token = $request->header('x-api-key');

        if( empty($token) ) {
            return Basic::DataJson(401,'login.authorizationTokenNotExist');
        }

        // 验证 Token
        $tokenObj = new Token();
        $obj = $tokenObj->check($token);

        if(is_null($obj)){
            return Basic::DataJson(401,'login.authorizationTokenInvalid');
        }

        $user = json_decode($obj,true);

        $request->token = $token;
        $request->user = $user;
        $request->user_id = $user['id'];
        $request->cusname = $user['cusname'];
        $request->phone = $user['phone'];
        $request->email = $user['email'];
        $request->role = $user['role'];

        return $next($request);
    }
}
